package com.wframe.project.jnd.dao;

import com.frame.database.JdataBean;
import com.wframe.framework.database.BaseDao;
import com.wframe.project.jnd.entity.Payment;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2017/5/12.
 */
@Repository
public class PaymentDao extends BaseDao {

    private String generateCode() {
        int retry = 0;
        String code = null;
        do {
            String time = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
            int max = 999999;
            int min = 100000;
            Random random = new Random();
            int randomNum = random.nextInt(max) % (max - min + 1) + min;
            String temp = time + String.valueOf(randomNum);
            Payment payment = getOrderByCode(temp);
            if (payment == null) {
                code = temp;
            }
            retry++;
        } while (StringUtils.isEmpty(code) && retry < 10);
        return code;
    }

    /**
     * 生成支付订单
     *
     * @param payment（amount：支付金额，order_type：订单类型，order_sn：订单编号）
     * @return 支付单
     */
    public Payment generateOrder(Payment payment) {
        if (payment != null && payment.getAmount() != null && payment.getAmount().compareTo(BigDecimal.ZERO) > 0 && payment.getOrder_type() != null && StringUtils.isNotEmpty(payment.getOrder_sn())) {
            String code = generateCode();
            if (StringUtils.isNotEmpty(code)) {
                Map<String, Object> datas = new HashMap<String, Object>();
                datas.put("sn", code);
                datas.put("amount", payment.getAmount());
                datas.put("pay_way", payment.getPay_way() == null ? null : payment.getPay_way().toString());
                datas.put("order_type", payment.getOrder_type().toString());
                datas.put("order_sn", payment.getOrder_sn());
                datas.put("pay_state", Payment.PayState.GENERATED.toString());
                datas.put("create_time", new Date());
                int result = 0;
                try {
                    result = super.save("wb_payment", datas);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (result == 1) {
                    return getOrderByCode(code);
                }
            }
        }
        return null;
    }

    /**
     * 根据支付单号查询支付单
     *
     * @param payCode 支付单号
     * @return 支付单
     */
    public Payment getOrderByCode(String payCode) {
        if (StringUtils.isNotEmpty(payCode)) {
            String sql = " SELECT * FROM wb_payment WHERE sn = ? ";
            List<JdataBean> jdataBeans = super.querySql(sql, new Object[]{payCode.toString()});
            if (jdataBeans != null && jdataBeans.size() > 0) {
                JdataBean jdataBean = jdataBeans.get(0);
                if (jdataBean != null && jdataBean.getlong("id") > 0L) {
                    Payment payment = new Payment();
                    payment.setId(jdataBean.getlong("id"));
                    payment.setSn(jdataBean.getString("sn"));
                    payment.setAmount(jdataBean.getBigDecimal("amount"));
                    payment.setOrder_type(Payment.PayOrderType.valueOf(jdataBean.getString("order_type")));
                    payment.setOrder_sn(jdataBean.getString("order_sn"));
                    payment.setPay_way(Payment.PayWay.valueOf(jdataBean.getString("pay_way")));
                    payment.setPay_sn(jdataBean.getString("pay_sn"));
                    payment.setPay_state(Payment.PayState.valueOf(jdataBean.getString("pay_state")));
                    payment.setCreate_time((Date) jdataBean.get("create_time"));
                    payment.setPay_time((Date) jdataBean.get("pay_time"));
                    payment.setRefund_time((Date) jdataBean.get("refund_time"));
                    payment.setFail_reason(jdataBean.getString("fail_reason"));
                    payment.setRemark(jdataBean.getString("remark"));
                    return payment;
                }
            }
        }
        return null;
    }

    /**
     * 根据pay_Sn查询对应支付订单总额
     */
    public BigDecimal getAmoutAll(String sn) {
        if (StringUtils.isNotBlank(sn)) {
            String sql = "select  IFNULL(SUM(p1.amount), 0) AS pay_amount from wb_payment p1"
                    + " left Join  wb_payment p2 on p1.order_type = p2.order_type"
                    + " AND p1.order_sn = p2.order_sn"
                    + " where p1.pay_state = 'SUCCESS' and p2.sn=?";
            BigDecimal AmoutAll = super.getObject(sql, new Object[]{sn}).getBigDecimal("pay_amount");
            return AmoutAll;
        }
        return null;
    }


    public void updateSubmitted(String sn) {
        String sql = "update wb_payment set pay_state=? WHERE sn=? and pay_state=?";
        operate(sql, new Object[]{Payment.PayState.SUBMITTED.name(), sn, Payment.PayState.GENERATED.name()});
    }

}
